package com.gopay.bis.gdb.wap.operation;

import com.gopay.bis.common.util.BankLogUtils;
import com.gopay.bis.gdb.wap.gfbank.payment.merchant.SignAndVerify;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.gdb.ebank.GdbB2cMessage;
import com.gopay.common.exception.GopayException;
import com.gopay.remote.bank.ICertHelper;

/**
 * 广发银行Wap网关签名验签类
 * 
 * @GdbWapCertHelper.java
 * @author lilili
 * @2017-03-23 上午9:32:24 www.gopay.com.cn Inc.All rights reserved.
 */
public class GdbWapCertHelper implements ICertHelper {

	 @Override
	    public String sign(BaseMessage baseMessage) throws GopayException {
	        try {
	            BankLogUtils.printB2CSignPlainLog(baseMessage);

	            String signResult = SignAndVerify.sign_md(baseMessage.getPlainMessage(), "");
	            if (signResult.length() > 10) {
	                // 如果签名成功将返回签名结果，长度远远大于十位
	                BankLogUtils.printB2CSignSignatureLog(baseMessage, signResult);
	                return signResult;
	            } else {
	                // 如果签名失败，返回1位的错误代码
	                baseMessage.setSpecial("errorCode = " + signResult);
	                BankLogUtils.printB2CSignExceptionLog(baseMessage, null);
	                throw new GopayException(ProcCodeConstants.PROC_CODE_100E6029);
	            }
	        } catch (Exception e) {
	            BankLogUtils.printB2CSignExceptionLog(baseMessage, e);
	            throw new GopayException(ProcCodeConstants.PROC_CODE_100E6029);
	        }
	    }

	    @Override
	    public Object verify(BaseMessage baseMessage) throws GopayException {
	        try {
	            GdbB2cMessage messageB2C = (GdbB2cMessage) baseMessage;
	            boolean isVerify;
	            BankLogUtils.printB2CVerifyPlainLog(messageB2C);
	            BankLogUtils.printB2CVerifySignatureLog(messageB2C, messageB2C.getSignMessage());

	            String status = SignAndVerify.verify_md(messageB2C.getPlainMessage(), messageB2C.getSignMessage(), "");
	            if (status.equals("0")) {
	                // 验证签名通过
	                isVerify = true;
	                BankLogUtils.printB2CVerifyResultLog(messageB2C, isVerify);
	            } else {
	                isVerify = false;
	                BankLogUtils.printB2CVerifyResultLog(messageB2C, isVerify);
	                messageB2C.setSpecial("status = " + status);
	                // 输出验签失败错误码
	                BankLogUtils.printB2CVerifyExceptionLog(messageB2C, null);
	            }
	            return isVerify;
	        } catch (Exception e) {
	            BankLogUtils.printB2CVerifyExceptionLog(baseMessage, e);
	            throw new GopayException(ProcCodeConstants.PROC_CODE_100E6031);
	        }
	    }

}
